from rest_framework import serializers
from goods.models import SKUImage, SKU


class SKUSimpleSerializer(serializers.ModelSerializer):
    """ SKU表 简单 模型类序列化器 """

    class Meta:
        model = SKU
        fields = ["id", "name"]


class SKUImageSerializer(serializers.ModelSerializer):
    """ SKU图片 模型类序列化器"""

    class Meta:
        model = SKUImage
        fields = ["id", "sku", "image"]

    # TODO：上传图片到 FastDFS 方式② --- 在序列化器中重写 validate（相对方法①方便点 但不都没有复用性 建议FastDFS全局设置的方法）
    # 在校验的过程中介入实现图片上传 FastDFS，从image图片对象中提取图片数据，上传 FastDFS，然后有效数据中存储文件索引id保存mysql
    # def validate(self, attrs):
    #     from fdfs_client.client import Fdfs_client
    #     from django.conf import settings
    #     import os
    #
    #     image_file = attrs.get('image')   # 文件对象
    #     image_byte = image_file.read()   # 文件字节数据
    #
    #     config_path = os.path.join(settings.BASE_DIR, "utils/client.conf")
    #     conn = Fdfs_client(config_path)
    #
    #     return_dict = conn.upload_by_buffer(image_byte)
    #     """
    #     @return dict {
    #         'Group name'      : group_name,
    #         'Remote file_id'  : remote_file_id,
    #         'Status'          : 'Upload successed.',
    #         'Local file name' : '',
    #         'Uploaded size'   : upload_size,
    #         'Storage IP'      : storage_ip
    #     } if success else None
    #     """
    #     if not (return_dict and return_dict["Status"] == "Upload successed."):
    #         # 上传失败
    #         raise serializers.ValidationError("FastDFS上传图片失败")
    #
    #     image = return_dict["Remote file_id"]
    #     # 上传之后把有效数据里面的image字段更改为文件索引id值存入mysql
    #     attrs['image'] = image
    #
    #     return attrs
